package com.xiangxiao.rpan.gateway.filter;

import com.xiangxiao.rpan.gateway.constant.MdcConstant;
import com.xiangxiao.rpan.gateway.utils.IdUtil;
import com.xiangxiao.rpan.gateway.utils.ServletUtil;

import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/11/29 11:29
 */
@WebFilter(urlPatterns = "/*")
public class MDCFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {

  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse responses = (HttpServletResponse) res;
    HttpServletRequest requests = (HttpServletRequest) req;

    MDC.put(MdcConstant.TRACE_ID, IdUtil.fastUUID());
    MDC.put(MdcConstant.IP, ServletUtil.getClientIP(requests));
    try {
      chain.doFilter(requests, responses);
    } finally {
      MDC.clear();
    }
  }

  @Override
  public void destroy() {

  }

}
